package com.zoshine.zzg.controller;

import com.zoshine.zzg.annotation.DisableLoginCheck;
import com.zoshine.zzg.base.BaseResponse;
import com.zoshine.zzg.config.ProjectConfig;
import com.zoshine.zzg.constant.Session;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.pojo.Menu;
import com.zoshine.zzg.pojo.Role;
import com.zoshine.zzg.pojo.User;
import com.zoshine.zzg.respons.AppResponse;
import com.zoshine.zzg.service.PowerService;
import com.zoshine.zzg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * 权限/验证控制器
 *
 * @author 贾俊峰
 * @time 2017/6/20 15:30
 */
@RestController
@RequestMapping(value = "auth", method = RequestMethod.POST)
public class AuthController extends BaseController{
    @Autowired
    private ProjectConfig projectConfig;
//    private MenuService menuService;
    private UserService userService;
    private PowerService powerService;
//    @Autowired
//    public void setMenuService(MenuService menuService) {
//        this.menuService = menuService;
//    }
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Autowired
    public void setPowerService(PowerService powerService) {
        this.powerService = powerService;
    }

    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @param patchca 图形验证码
     */
    @DisableLoginCheck
    @RequestMapping("login")
    public BaseResponse login(String username, String password, String patchca, HttpSession session) throws Exception {
        if (Objects.equals(projectConfig.getEnvironment(), "outer")) {
            // 验证验证码
            String patchcaCheck = (String) session.getAttribute(Session.LOGIN_PATCHCA);
            if (patchcaCheck == null || !patchcaCheck.equalsIgnoreCase(patchca)) {
                throw new AppException(ErrorMessage.PATCHCA_ERROR);
            }
        }
        // 验证用户名密码
        User user = userService.loginCheck(username, password);
        session.setAttribute(Session.LOGIN_USER, user);

        refreshPower(session);
        return AppResponse.OK;
    }

    /**
     * 登出
     */
    @RequestMapping("logout")
    public BaseResponse logout(HttpSession session) {
        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            session.removeAttribute(name);
        }
        return AppResponse.OK;
    }

    /**
     * 刷新权限
     */
    @RequestMapping("refreshPower")
    public BaseResponse refreshPower(HttpSession session) {
        User user = (User) session.getAttribute(Session.LOGIN_USER);
        // 配置用户菜单权限
        List<Menu> menuPower = powerService.getMenuPower(user);
        session.setAttribute(Session.MENU_POWER, menuPower);
        if (Objects.equals(projectConfig.getEnvironment(), "bank")) {
            return AppResponse.OK;
        }
        // 配置监所权限
        List<Long> prisonPower = powerService.getPrisonPower(user);
        session.setAttribute(Session.PRISON_POWER, prisonPower);
        // 配置供应商权限
        List<Long> supplierPower = powerService.getSupplierPower(user);
        session.setAttribute(Session.SUPPLIER_POWER, supplierPower);
        return AppResponse.OK;
    }

    /**
     * 获取顶级菜单列表
     * @return 顶级菜单列表
     */
    @RequestMapping("listTopMenu")
    @SuppressWarnings("unchecked")
    public BaseResponse listTopMenu(HttpSession session) {
        List<Menu> menuPower = (List<Menu>) session.getAttribute(Session.MENU_POWER);
        List<Menu> menuList = new ArrayList<>();
        for (Menu menu : menuPower) {
            if (menu.getMenuLevel() == 1) {
                menuList.add(menu);
            }
        }
        return new AppResponse(menuList);
    }

    /**
     * 获取子菜单列表
     * @param parentId 父菜单编号
     * @return 子菜单列表
     */
    @RequestMapping("listSubMenu")
    @SuppressWarnings("unchecked")
    public BaseResponse listSubMenu(String parentId, HttpSession session) {
        List<Menu> menuPower = (List<Menu>) session.getAttribute(Session.MENU_POWER);
        List<Menu> menuList = new ArrayList<>();
        for (Menu menu : menuPower) {
            if (Objects.equals(menu.getParentId(), parentId)) {
                menuList.add(menu);
            }
        }
        return new AppResponse(menuList);
    }

    /**
     * 获取当前登录账号的菜单权限
     * @return 菜单列表
     */
    @RequestMapping("listMenu")
    @SuppressWarnings("unchecked")
    public BaseResponse listMenu(HttpSession session) {
        List<Menu> menuList = (List<Menu>) session.getAttribute(Session.MENU_POWER);
        return new AppResponse(menuList);
    }

    /**
     * 获取角色菜单权限
     * @param roleId 角色编号
     * @return 该角色拥有的菜单权限
     */
    @RequestMapping("listMenuByRole")
    public BaseResponse listMenuByRole(Long roleId) {
        System.out.println(roleId);
        Role role = new Role();
        role.setId(roleId);
        List<Menu> menuList = powerService.getMenuPower(role);
        return new AppResponse(menuList);
    }

    /**
     * 判断是否拥有权限
     * @param menuId 菜单编号
     */
    @RequestMapping("hasPower")
    @SuppressWarnings("unchecked")
    public BaseResponse hasPower(String menuId, HttpSession session) {
        List<Menu> menuPower = (List<Menu>) session.getAttribute(Session.MENU_POWER);
        for (Menu m : menuPower) {
            if (Objects.equals(m.getMenuId(), menuId)) {
                return new AppResponse(true);
            }
        }
        return new AppResponse(false);
    }

    /**
     * 设置角色权限
     * @param roleId 角色编号
     * @param menuPower 菜单权限
     */
    @RequestMapping("setRoleMenuPower")
    public BaseResponse setRoleMenuPower(Long roleId, String menuPower) {
        Role role = new Role();
        role.setId(roleId);
        if (StringUtils.isEmpty(menuPower)) {
            powerService.cleanMenuPower(role);
        } else {
            powerService.setMenuPower(role, menuPower);
        }
        return AppResponse.OK;
    }

    /**
     * 用户原密码验证
     * @param password 密码
     */
    @RequestMapping("validatePassword")
    public BaseResponse validatePassword(String password){
        if (password == null){
            throw new AppException(ErrorMessage.HISTORY_PASSWORD_IS_NOT_NULL);
        }
        User loginUser = getLoginUser();
        password = DigestUtils.md5DigestAsHex(password.getBytes()) + loginUser.getSalt();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!loginUser.getPassword().equals(password)){
            throw new AppException(ErrorMessage.HISTORY_PASSWORD_IS_NOT_CORRECT);
        }
        return AppResponse.OK;
    }

    /**
     * 密码修改
     * @param newPassword 新密码
     */
    @RequestMapping("checkPassword")
    public BaseResponse checkPassword(String newPassword){
        if (newPassword == null){
            throw new AppException(ErrorMessage.NEW_PASSWORD_IS_NOT_NULL);
        }
        User loginUser = getLoginUser();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes())+loginUser.getSalt();
        newPassword = DigestUtils.md5DigestAsHex(newPassword.getBytes());
        loginUser.setPassword(newPassword);
        userService.editPassword(loginUser);
        return AppResponse.OK;
    }
}
